﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace iLangl.Transport.Extensions
{
	/// <summary>
	/// Extention to stream classes.
	/// </summary>
	public static class StreamExtentions
	{
		#region static methods

		/// <summary>
		/// Determines whether this file has the same content as another file.
		/// </summary>
		/// <param name="stream">This file</param>
		/// <param name="otherStream">Another file.</param>
		/// <returns>
		/// 	<c>true</c> if this file has the same content as another file; otherwise, <c>false</c>.
		/// </returns>
		public static Boolean HasSameContent(this FileStream file, FileStream otherFile)
		{
			Int64 streamPosition = file.Position;
			Int64 otherStreamPosition = otherFile.Position;

			try
			{
				file.Seek(0, SeekOrigin.Begin);
				otherFile.Seek(0, SeekOrigin.Begin);

				if (file.Length != otherFile.Length)
					return false;

				for (Int32 byteIndex = 0; byteIndex < file.Length; byteIndex++)
				{
					if (file.ReadByte() != otherFile.ReadByte())
						return false;
				}

				return true;
			}
			finally
			{
				file.Seek(streamPosition, SeekOrigin.Begin);
				otherFile.Seek(streamPosition, SeekOrigin.Begin);
			}
		}

		/// <summary>
		/// Writes stream content to file.
		/// </summary>
		/// <param name="stream">The stream.</param>
		/// <param name="destinationFilePath">Path of the destination file.</param>
		public static void WriteToFile(this Stream stream, String destinationFilePath)
		{
			using (FileStream destinationStream = new FileStream(destinationFilePath, FileMode.Create))
			{
				Int32 bufferSize = 4096;
				Byte[] buffer = new Byte[bufferSize];
				Int32 bytesRead;
				while ((bytesRead = stream.Read(buffer, 0, bufferSize)) != 0)
				{
					destinationStream.Write(buffer, 0, bytesRead);
				}
			}
		}

		#endregion
	}
}
